import {
  reactive,
  ref,
  computed,
  onMounted,
  onUnmounted,
  getCurrentInstance,
} from "vue";
import globalStyles from "@gd-accbuild-core/theme-chalk/pc-admin/js.module.scss";

/**
 * 获取当前选中的CRUD key的前缀
 * @param {String | "table" | "main" | "tree"} curPickedCrudContainerKey
 * main用于 "树 + 插槽"单视图模板、table用于 "表格、表单"单视图模板、tree用于 "左树右表"双视图模板
 */
export const getCurPickedTargetSuffix = (curPickedCrudContainerKey) => {
  let targetSuffix = "";
  if (["table", "main"].includes(curPickedCrudContainerKey)) {
    targetSuffix = "";
  } else {
    targetSuffix = `_${curPickedCrudContainerKey}`;
  }
  return targetSuffix;
};

export default ({
  props,
  curTemplateAllCrudContainerKeys = ["table"],
  crudServiceVmTemplateConfig,
}) => {
  const { proxy: vm } = getCurrentInstance();
  /**
   * 定义CRUD组件的DOMref以及设计时点击事件监听
   */
  const crudContainerClickEvents = {};

  onMounted(() => {
    if (props.canvasRenderConfig.enable) {
      setTimeout(() => {
        curTemplateAllCrudContainerKeys.forEach((key) => {
          crudContainerClickEvents[key] =
            props.canvasRenderConfig.templateEvents({
              targetSuffix: getCurPickedTargetSuffix(key),
              canvasRenderPickedComp: canvasRenderPickedComp,
            })["click"];
          const intervalId = setInterval(() => {
            //TODO:FIXME: biz组件必须按照规范设置css
            const matchedDom = vm.$el.querySelector(
              `.${key}-container .${key}-content`
            );
            if (matchedDom) {
              clearInterval(intervalId);
              matchedDom.addEventListener(
                "click",
                crudContainerClickEvents[key]
              );
            }
          }, 1000);
        });
      }, 2000);
    }
  });
  onUnmounted(() => {
    if (props.canvasRenderConfig.enable) {
      curTemplateAllCrudContainerKeys.forEach((key) => {
        const matchedDom = vm.$el.querySelectorAll(
          `.${key}-container>.${key}-content`
        )[0];
        if (matchedDom) {
          matchedDom.removeEventListener(
            "click",
            crudContainerClickEvents[key]
          );
        }
      });
    }
  });

  /**
   * 当前CRUD模板组件 容器的宽高等属性;默认一个业务模板组件 满屏一页
   */
  const templateContainerAttr = ref({
    width: `calc(100vw - ${globalStyles.accbuildPageLeftWindowContainerWidth})`,
  });
  const canvasRenderPickedComp = reactive({
    targetSuffix: "",
  });

  /**
   * 当前CRUD模板组件 内所有子CRUD的设计时绑定事件;仅绑定设计时事件，运行时事件不在这里
   */
  const getCrudContainerKeyEvent = (crudContainerKey) => {
    const targetSuffix = getCurPickedTargetSuffix(crudContainerKey);
    return (
      props.canvasRenderConfig?.templateEvents ??
      (() => {
        return {};
      })
    )({
      targetSuffix,
      canvasRenderPickedComp: canvasRenderPickedComp,
    });
  };

  /**
   * 获得模板 内指定CRUD组件的设计时样式：选中时边框高亮等
   */
  const getClassObjInBizTemplateCrudContainerWhenRender = (
    crudContainerKey
  ) => {
    const targetSuffix = getCurPickedTargetSuffix(crudContainerKey);
    return {
      "biz-template-container--canvas-render": props.canvasRenderConfig.enable,
      "biz-template-container--canvas-render--hover-allow":
        canvasRenderPickedComp.targetSuffix !== targetSuffix,
      "biz-template-container--canvas-render_picked":
        canvasRenderPickedComp.targetSuffix === targetSuffix,
    };
  };
  /** 是否当前组件渲染在设计器中 */
  const isDesigner = computed(() => {
    return (
      (crudServiceVmTemplateConfig.tree &&
        crudServiceVmTemplateConfig.tree.hasOwnProperty(
          "_gdAccbuild_GdSysProject_proxyFlag"
        )) ||
      (crudServiceVmTemplateConfig.table &&
        crudServiceVmTemplateConfig.table.hasOwnProperty(
          "_gdAccbuild_GdSysProject_proxyFlag"
        ))
    );
  });
  /**
   * 设置模板容器尺寸：设计时、运行时
   */
  const setterTemplateContainerAttr = (templateState) => {
    templateContainerAttr.value = templateState.curPageUiTemplateConfig
      .templateProps?.templateContainerAttr ?? {
      width: `calc(100vw - ${globalStyles.accbuildPageLeftWindowContainerWidth})`,
    };
    if (
      isDesigner.value &&
      props.canvasRenderConfig.hasOwnProperty("templateContainerAttr")
    ) {
      templateContainerAttr.value.width =
        props.canvasRenderConfig?.templateContainerAttr?.width ??
        `calc(100vw - ${globalStyles.accbuildPageLeftWindowContainerWidth})`;
    }
  };
  return {
    /** 是否当前组件渲染在设计器中 */
    isDesigner,
    templateContainerAttr,
    /** 设置模板容器尺寸：设计时、运行时 */
    setterTemplateContainerAttr,
    getCrudContainerKeyEvent,
    /** 获得模板 内指定CRUD组件的设计时样式：选中时边框高亮等 */
    getClassObjInBizTemplateCrudContainerWhenRender,
    canvasRenderPickedComp,
  };
};
